<template>
  <ContentWrap>
    <el-row type="flex" :gutter="24">
      <el-col :span="10">
        <ContainerTitle title="质检内容">
          <List :column="2" default-value="--" sep="：">
            <ListItem label="受检人" :value="`${insData.litigantName}(${insData.litigant})`" />
            <ListItem label="所属业务组" :value="insData.litigantBusinessGroupName" />
            <ListItem label="通话记录编号" :span="24" :value="insData.callCode">
              <div slot="content" :class="[$style.callCode, 'custom-list-item']">
                <span class="label-style" style="width: auto; position: relative; padding-right: 4px;">通话记录编号<span>：</span></span>
                <span>{{ insData.callCode }}</span>
                <PhonePlay ref="phonePlay" :voice="callRecord" :step-time="5" show-btn style="margin-left: 10px;"></PhonePlay>
              </div>
            </ListItem>
            <ListItem label="联系电话" :value="callRecord.customerPhone" />
            <ListItem label="呼叫类型" dict-type-code="CALL_TYPE" :value="insData.callType" />
            <ListItem label="通话时长" :value="callRecord.talkTime" />
            <ListItem label="工单编号" :span="24" :value="insData.workOrderCode" :value-class-name="`table-click-text ${$style.valueClassName}`" @click="toWorkOrderHandle(insData.workOrderCode)" />
            <ListItem label="一级业务类型" :value="insData.businessType1Name" />
            <ListItem label="二级业务类型" :value="insData.businessType2Name" />
            <ListItem label="满意度" dict-type-code="SATISFACTION" :value="callRecord.satisfaction" />
            <ListItem label="顾客评价" dict-type-code="EVALUATE_STAFF" :value="callRecord.evaluateType" />
          </List>
        </ContainerTitle>
        <ContainerTitle v-if="isAllege" title="质检结果" style="margin-top:10px">
          <List :column="3" default-value="--" sep="：">
            <ListItem label="是否微笑服务" :value="insData.isSmile===0?'否':insData.isSmile===1?'是':''" />
            <ListItem label="等级" :value="getDictName(insData.level, lelveList)" />
            <ListItem label="质检得分" :value="insData.score" />
            <ListItem label="标记典型" :span="24" :value="insData.typicalType===1?'正面':insData.typicalType===2?'负面':''" />
            <ListItem label="标记典型原因" :span="24" :value="insData.typicalCause" />
          </List>
        </ContainerTitle>
        <ContainerTitle :title="isAllege?'申诉评定':'质检评定'" style="margin-top:10px">
          <List v-if="isAllege" :column="1" default-value="--" sep="：" label-width="80px" style="margin-bottom:5px">
            <ListItem label="申诉原因" :value="insData.appealCause" />
          </List>
          <FormContainer :column="2">
            <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
              <el-form-item prop="isSmile" label="是否微笑服务">
                <el-select v-model="formData.isSmile" filterable clearable placeholder="请选择">
                  <el-option v-for="(d,i) in smileStateList" :key="i" :value="d.dictCode" :label="d.dictName"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="level" label="等级">
                <el-select v-model="formData.level" filterable clearable placeholder="请选择">
                  <el-option v-for="(d,i) in lelveList" :key="i" :value="d.dictCode" :label="d.dictName"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="typicalType" label="典型">
                <el-select v-model="formData.typicalType" filterable clearable placeholder="请选择">
                  <el-option v-for="(d,i) in modelList" :key="i" :value="d.dictCode" :label="d.dictName"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="score" :label="isAllege?'申诉得分':'质检得分'">
                <el-input v-model="formData.score" v-number-input.float disabled readonly clearable placeholder="请输入得分"></el-input>
              </el-form-item>
              <el-form-item prop="typicalCause" label="标记典型原因" :span="24">
                <el-input v-model="formData.typicalCause" type="textarea" :autosize="{minRows:3}" placeholder="请输入原因"></el-input>
              </el-form-item>
              <el-form-item :span="24">
                <div :class="$style.btn">
                  <Button type="primary" :disabled="disabled" @click="submitHandle">提交</Button>
                  <Button type="primary" @click="cancelHadnle">取消</Button>
                </div>
              </el-form-item>
            </el-form>
          </FormContainer>
        </ContainerTitle>
      </el-col>
      <el-col :span="14">
        <div :class="$style.paperWrap">
          <el-scrollbar>
            <div :class="$style.container">
              <Preview :id="questionnaireId" is-preview @on-confirm="onConfirmHandle"></Preview>
            </div>
          </el-scrollbar>
        </div>
      </el-col>
    </el-row>
  </ContentWrap>
</template>
<script>
import { List, ListItem } from '@/components/List'
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import ContainerTitle from '../../components/containerTitle'
import Preview from '../../components/preview'
import PhonePlay from '@/components/PhonePlay'
import { lelveList, smileStateList, modelList } from '../../common'
import { qualityCheckTaskDetail, qualityCheck, qualityCheckTaskAppealQualityCheck, qualityCheckProjectDetail, qualityCheckTaskGrade, qualityCheckTaskAppealGrade } from '@/api/inspection'
import { getCallRecordByCallCode } from '@/api/telRecord'
import { deepCopy } from '@/utils'
function resultObj(taskId, questionId, optionId, score, description, answer) {
  return {
    optionId,	// 选项ID
    questionId, //	问题id
    score, //	得分
    taskId, //	任务ID
    description,
    answer
  }
}
export default {
  name: 'EvalScore',
  components: {
    List,
    ListItem,
    ContentWrap,
    FormContainer,
    ContainerTitle,
    Preview,
    PhonePlay
  },
  props: {
    isAllege: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      insData: {},
      questionnaireId: '',
      formData: {
        isSmile: '',
        level: '',
        typicalType: '',
        score: '',
        typicalCause: ''
      },
      formRules: {

      },
      results: [], // 质检表结果
      callRecord: {}, // 通话信息
      disabled: true,
      smileStateList,
      lelveList,
      modelList
    }
  },
  created() {
    this.getInsData()
  },
  methods: {
    submitHandle() {
      return this.$refs.form.validate().then(() => {
        const data = deepCopy(this.formData)
        let ajax = qualityCheck
        if (this.isAllege) {
          ajax = qualityCheckTaskAppealQualityCheck
          data.appealIsSmile = data.isSmile
          delete data.isSmile
          data.appealLevel = data.level
          delete data.level
          data.appealTypicalType = data.typicalType
          delete data.typicalType
          data.appealScore = data.score
          delete data.score
          data.appealTypicalCause = data.typicalCause
          delete data.typicalCause
        }
        data.id = this.id
        return ajax(data).then(res => {
          this.$message.success('提交成功！')
          this.$closePage()
        })
      })
    },
    cancelHadnle() {
      this.$closePage()
    },
    // 工单详情页
    toWorkOrderHandle(workOrderNo) {
      if (!workOrderNo) {
        this.$message.error('没有工单编号！')
        return
      }
      this.$router.push({ name: 'QueryOrderDetails', query: { workOrderNo, form: 'any' }})
    },
    // 获取详情
    getInsData() {
      qualityCheckTaskDetail(this.id).then(res => {
        this.insData = res.data
        // 获取通话信息
        if (res.data.callCode) {
          getCallRecordByCallCode(res.data.callCode).then(res => {
            if (res.data.records.length > 0) {
              this.callRecord = res.data.records[0]
            }
          }).catch(() => {
            this.$message.error('获取通话信息失败！')
          })
        }
        // 获取问卷id
        return qualityCheckProjectDetail(this.insData.projectId).then(res => {
          this.questionnaireId = res.data.questionnaireId
        }).catch(() => {
          this.$message.error('获取质检表失败！')
        })
      })
    },
    getDictName(dictCode, list) {
      return this.$getNameByDataDict(dictCode, list)
    },
    // 收集质检结果
    onConfirmHandle(data) {
      // console.log(data)
      // eslint-disable-next-line prefer-const
      let { results, sumScore, noAnswerList } = this.genResults(data)
      if (noAnswerList.length > 0) {
        this.$message.warning(`答题不全！`)
        noAnswerList.forEach((e, i) => {
          this.scorllView(e, i === 0)
        })
        return Promise.reject('答题不全！')
      }
      let ajax = qualityCheckTaskGrade
      if (this.isAllege) {
        ajax = qualityCheckTaskAppealGrade
        results = this.setOptionId(results)
      }
      // this.$emit('on-answer', results, sumScore)
      this.results = results

      const d = {
        results,
        // score: sumScore,
        id: this.id
      }
      return ajax(d).then(res => {
        this.disabled = false
        this.$set(this.formData, 'score', sumScore)
        this.$message.success('操作成功！')
      })
    },
    // 如果是申诉质检则需要id
    setOptionId(results) {
      for (const result of results) {
        const { questionId } = result
        for (const rawResult of this.insData.results) {
          if (questionId === rawResult.questionId) {
            result.id = rawResult.id
            break
          }
        }
      }
      return results
    },
    // 收集结果
    genResults(data) {
      let results = []
      let sumScore = 0
      const noAnswerList = []
      const sum = scoreValue => { !isNaN(scoreValue) ? sumScore += scoreValue : '' }
      for (const chapter of data.questionnaireChapterDTOList) {
        // const cid = chapter.id
        for (const question of chapter.questionnaireQuestionDTOList) {
          const questionId = question.id
          const result = question.result
          const enterContent = question.enterContent
          // 单选
          if (question.questionType === 0) {
            if (result === '' || result === undefined) {
              noAnswerList.push(question.id)
              continue
            }
            const o = question.questionOptionDTOList[result]
            sum(o.scoreValue)
            results.push(resultObj(this.id, questionId, o.id, o.scoreValue, enterContent[result], ''))
          } else if (question.questionType === 1) { // 多选
            if (!(result instanceof Array) || result.length <= 0) {
              noAnswerList.push(question.id)
              continue
            }
            for (const i of result) {
              const o = question.questionOptionDTOList[i]
              sum(o.scoreValue)
              results.push(resultObj(this.id, questionId, o.id, o.scoreValue, enterContent[i], ''))
            }
          } else if (question.questionType === 2) { // 填空
            if (!enterContent || Object.keys(enterContent).length <= 0) {
              noAnswerList.push(question.id)
              continue
            }
            for (const i of Object.keys(enterContent)) {
              const o = question.questionOptionDTOList[i]
              sum(o.scoreValue)
              results.push(resultObj(this.id, questionId, o.id, o.scoreValue, '', enterContent[i]))
            }
          }
        }
      }
      if (this.isAllege) {
        results = results.map(e => {
          return {
            appealAnswer: e.answer,
            appealDescription: e.description,
            appealOptionId: e.optionId,
            appealScore: e.score,
            questionId: e.questionId,
            taskId: e.taskId
          }
        })
      }
      return { results, sumScore, noAnswerList }
    },
    // 将未答题目滚动到可视区域
    scorllView(id, view = true) {
      const ele = document.getElementById(id)
      ele.parentElement.classList.add('noAnswer')
      if (view) {
        ele.scrollIntoView()
      }
    }

  }
}
</script>
<style lang="scss" module>
.btn{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.paperWrap{
  border: 1px solid #eee;
  border-radius: 8px;
  height: 100%;
}
.container{
  padding-top: 10px;
  max-height: 700px;
}
.valueClassName{
  color: #11A265 !important;
}
.callCode{
  align-items: center;
}
</style>
<style>
.noAnswer{
  outline: 1px auto red;
  outline-offset: 4px;
}
</style>
